using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace LeisureCenter.Api.Tools
{
    public class SerializableDictionary<K, V> : Dictionary<K, V>, IXmlSerializable
    {
        #region IXmlSerializable Membres

        protected virtual string NS { get { return "http://www.cfagn.net/leisurecenter"; } }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlSerializer keySer = new XmlSerializer(typeof(K));
            XmlSerializer valueSer = new XmlSerializer(typeof(V));

            reader.Read();
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item", NS);

                reader.ReadStartElement("key", NS);
                K key = (K)keySer.Deserialize(reader);
                reader.ReadEndElement();

                reader.ReadStartElement("value", NS);
                V value = (V)valueSer.Deserialize(reader);
                reader.ReadEndElement();

                Add(key, value);

                reader.ReadEndElement();
                reader.MoveToContent();
            }
        }

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySer = new System.Xml.Serialization.XmlSerializer(typeof(K), NS);
            XmlSerializer valueSer = new System.Xml.Serialization.XmlSerializer(typeof(V), NS);
            foreach (K key in Keys)
            {
                writer.WriteStartElement("item", NS);

                writer.WriteStartElement("key", NS);
                keySer.Serialize(writer, key);
                writer.WriteEndElement();

                writer.WriteStartElement("value", NS);
                V value = this[key];
                valueSer.Serialize(writer, value);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }

        #endregion
    }
}
